<template>
  <section :class="['menu-box', menuMini ? 'menu-mini' : '', 'transform_5']">
    <header class="head" style="background:#3f434a;">
      <img v-if="hospital.picture" :src="hospital.picture | imageUrl" />
      <img v-else src="/img/logo.png" />
      <p v-if="!animationExecute" class="title">{{ hospital.hospitalName }}</p>
    </header>
    <div class="list-box">
      <div class="no-scroll">
        <div v-for="(item, index) in meunArr" :key="index" class="item-box">
          <section v-if="item.child">
            <div class="title">{{ item.name }}</div>
            <div v-for="(obj, index) in item.child" :key="index" :class="['menu-item', isCur(obj)]" :title="menuMini ? obj.name : ''" @click="clickUrl(obj)">
              <i :class="['iconfont', obj.icon]"></i>
              <span class="vertical-middle">{{ obj.name }}</span>
            </div>
          </section>
          <div v-else :class="['menu-item', isCur(item)]" :title="menuMini ? item.name : ''" @click="clickUrl(item)">
            <i :class="['iconfont', item.icon]"></i>
            <span class="vertical-middle">{{ item.name }}</span>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
<script>
import { mapState, mapGetters } from "vuex";
export default {
  computed: {
    ...mapState(["menuMini"])
  },
  data() {
    return {
      defaultActive: "",
      animationExecute: false,
      meunArr: [],
      hospital: {},
      // 当前路由匹配到的菜单项
      currentRouteObjectOfMenuArray: null
    };
  },
  async created() {
    let th = this;
    th.animationExecute = th.menuMini;
    th.getMenu();
  },
  mounted() {
    let th = this;
    th.getHospital();
  },
  methods: {
    //获取医院
    getHospital() {
      let th = this;
      let j = {
        id: th.adminUser.hpId
      };
      th.$api.getHospitalById(j).then(res => {
        if (res.executed) {
          th.hospital = res.dataBody.list[0];
          th.$store.state.adminUser["hospitalName"] = th.hospital.hospitalName;
          th.$store.state.adminUser["hospitalLogo"] = th.hospital.picture;
          th.$store.state.adminUser["hospitalProvince"] = th.hospital.province;
          th.$store.state.adminUser["hospitalCity"] = th.hospital.city;
          th.$store.state.adminUser["hospitalDistrict"] = th.hospital.district;
          th.$store.state.adminUser["hospitalAddress"] = th.hospital.address;
          //要加服务器地址
          th.$store.state.adminUser["printLogo"] = th.$config.imageUrl + th.hospital.writeLogoUrl;
        }
      });
    },
    clickUrl: function(obj) {
      let th = this;
      let signArr = obj.url.split("/");
      let sign = signArr[signArr.length - 1];
      let url = obj.url;
      //判断是否第二次点击（刷新页面）
      if (th.$route.path == obj.url) {
        th.$store.commit("Del_includeCom", sign);
        th.$root.showView = false;
        setTimeout(() => {
          th.$root.showView = true;
          th.$store.state.includeCom.push(sign);
        }, 100);
      } else {
        this.getTitleSign(obj);
        th.addNavMenu(obj.name, obj.url, ""); //这里取消加缓存，在需要的页面加
        th.$router.push(obj.url);
      }
    },
    //读取菜单当前菜单和图标（展示在top）
    getTitleSign(data) {
      let th = this;
      let j = { icon: data.icon, name: data.name };
      th.$store.commit("Set_curPage", j);
    },
    //获取菜单数据
    getMenu() {
      let th = this;
      let j = {
        adminRoleId: th.adminUser.roleId
      };

      /**
       * 根据route获取菜单项，然后设置标题
       * @param obj
       */
      const findCurrentRouteObject = obj => {
        if (!this.currentRouteObjectOfMenuArray && obj.url === this.$route.path) {
          this.currentRouteObjectOfMenuArray = obj;
          this.getTitleSign(obj);
        }
      };

      th.$api.getRolePermissions(j).then(res => {
        if (!res.executed) {
          return;
        }
        for (let i = 0; i < res.dataBody.permissions.length; i++) {
          let element = res.dataBody.permissions[i];
          if (!element.check) continue;
          let json = {
            name: element.description,
            permissionId: element.permissionId,
            icon: element.icon
          };
          if (element.childPermission && element.childPermission.length > 0) {
            let child = [];
            for (let g = 0; g < element.childPermission.length; g++) {
              let elementSon = element.childPermission[g];
              if (!elementSon.check) continue;
              let jsonSon = {
                name: elementSon.description,
                permissionId: elementSon.permissionId,
                url: elementSon.url,
                icon: elementSon.icon
              };
              findCurrentRouteObject(jsonSon);
              child.push(jsonSon);
            }
            json["child"] = child;
          } else {
            findCurrentRouteObject(json);
            json["url"] = element.url;
          }
          //更新icon
          th.meunArr.push(json);
        }
        th.jsonMenu();
      });
    },
    //解析数据生成菜单json
    jsonMenu() {
      let th = this;
      let oneData = th.meunArr[0];
      if (oneData.child && oneData.child.length > 0) {
        oneData = oneData.child[0];
      }
      oneData.isCur = true;
      let urlArr = oneData.url.split("/");
      //设置权限
      th.$store.commit("Set_qxId", oneData.permissionId);
      //设置第一个菜单为当前菜单显示
      this.currentRouteObjectOfMenuArray ||
        th.$store.commit("Set_curPage", {
          name: oneData.name,
          icon: oneData.icon
        });
      //快捷菜单下标
      th.$store.commit("Set_navRouterIndex", 0);
      //设置快捷菜单
      th.$store.commit("set_navMenuList", [
        {
          name: oneData.name,
          url: oneData.url,
          sign: urlArr[urlArr.length - 1]
        }
      ]);
      th.$store.commit("Set_menuArray", th.meunArr);
    },
    isCur(obj) {
      let th = this;
      let result = "";
      if (th.defaultActive == obj.url) {
        result = "cur";
      }
      return result;
    }
  },
  watch: {
    menuMini(n) {
      let th = this;
      if (n) {
        th.animationExecute = n;
      } else {
        setTimeout(() => {
          th.animationExecute = n;
        }, 300);
      }
    },
    $route: {
      handler: function(n, o) {
        let th = this;
        let meta = n.meta.path;
        if (meta) {
          let str = n.path.substring(0, n.path.lastIndexOf("/") + 1);
          th.defaultActive = str + meta;
        } else {
          th.defaultActive = n.path;
        }
      },
      immediate: true
    }
  },
  components: {}
};
</script>
